import {WEB_NAME} from "@/common/static.js"
import { createRouter, createWebHashHistory } from 'vue-router'


// 主页面
const Login = ()=>import("@/entry/Login/Index.vue")
const Index = () => import("@/entry/index/App.vue")
const Error = () => import("@/entry/Error/404.vue")
const Show = ()=> import('@/entry/Show/Show.vue')

function LoadRoutes() {
  const MainRoutes = import.meta.globEager("@/views/*/route.js")
  return Object.values(MainRoutes).map((item) => item.default)
}

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      // redirect: '/home',
      component:Show,
      meta: {
        title: WEB_NAME,
      },
    },
    {
      path:'/index',
      name:'Index',
      component: Index,
      children: [
        ...LoadRoutes()
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component:Login
    },
    {
      path: "/404",
      name:"NotFound",
      component:Error,
    },
    {
      path: '/:pathMatch(.*)',
      redirect:'/404'
    },
    
    // {
    //   path: '/',
    //   name: 'home',
    //   component: HomeView
    // },
    // {
    //   path: '/about',
    //   name: 'about',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('../views/AboutView.vue')
    // }
  ]
})

router.beforeEach((to, form, next) => {
  if (to.path === '/' || to.path === '/404') {
    next()
  } else {
    const token = localStorage.getItem('token')

    if (token === null || token === '') {
      if (to.path === '/login') {
        next()
      } else {
        alert('您还没有登录，请先登录')
        next('/login')
      }
      
    } else if(to.path === '/login') {
      next('/home')
    } else {
      next()
    }
  }
})

export default router
